package cn.agiledata.bank.audit.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AuditGroup;
import com.vnv.infrastructure.logic.IPBHibernate3BaseMgr;

/**
 * @author 马贤波
 * 
 */
public class AuditGroupDaoImpl extends IPBHibernate3BaseMgr implements
        IAuditGroupDao {
    public AuditGroup[] getAuditGroups(boolean systemGroup, Long accountId,
            Boolean updatable) {
        String hql = "from AuditGroup ag where ag.systemGroup=? ";
        List params = new ArrayList();
        params.add(new Boolean(systemGroup));
        if (accountId == null) {
            hql += "and ag.account is null ";
        } else {
            hql += "and ag.account.id=? ";
            params.add(accountId);
        }
        if (updatable != null) {
            hql += "and ag.updatable=? ";
            params.add(updatable);
        }
        List resultList = getHibernateTemplate().find(hql, params.toArray());
        return (AuditGroup[]) resultList.toArray(new AuditGroup[0]);
    }

    public AuditGroup getAuditGroupByName(boolean systemGroup, Account account,
            String name) {
        String hql = "from AuditGroup ag where ag.systemGroup=? and ag.name=? ";
        Object[] params;
        if (account == null) {
            hql += "and ag.account is null";
            params = new Object[] { new Boolean(systemGroup), name };
        } else {
            hql += "and ag.account=?";
            params = new Object[] { new Boolean(systemGroup), name, account };
        }
        HibernateTemplate ht = getHibernateTemplate();
        int maxResults = ht.getMaxResults();
        ht.setMaxResults(1);
        List resultList = ht.find(hql, params);
        ht.setMaxResults(maxResults);
        return resultList.size() == 0 ? null : (AuditGroup) resultList.get(0);
    }

    public void saveOrUpdateAuditGroup(AuditGroup auditGroup) {
        this.getHibernateTemplate().saveOrUpdate(auditGroup);
        this.getHibernateTemplate().flush();
    }

    public AuditGroup getAuditGroupById(long auditGroupId) {
        return (AuditGroup) getHibernateTemplate().get(AuditGroup.class,
                new Long(auditGroupId));
    }

    public void deleteAuditGroup(AuditGroup auditGroup) {
        getHibernateTemplate().delete(auditGroup);
        getHibernateTemplate().flush();
    }

}